2-sat dfs and similar dsu graphs *1900

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;

int n, m, u, v, ans = 0;
bool w, c[101], vi[101];
struct edge{
	int u, v;
	bool w;
};
vector<pair<int, bool>> g[101];
vector<edge> e;
queue<int> q;

void bfs(int s) {
	vi[s] = true; q.push(s);
	while (!q.empty()) {
		u = q.front();
		q.pop();
		for (auto [v, w] : g[u]) if (!vi[v])
			vi[v] = true, c[v] = w ^ c[u], q.push(v);
	}
}

signed main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cin >> n >> m;
	while (m--) {
		cin >> u >> v >> w; w = !w;
		g[u].push_back({v, w});
		g[v].push_back({u, w});
		e.push_back({u, v, w});
	}
	for (int i = 1; i <= n; i++) if (!vi[i]) bfs(i);
	for (auto [u, v, w] : e) if (c[u] ^ c[v] != w)
		return cout << "Impossible", 0;
	for (int i = 1; i <= n; i++) ans += c[i];
	cout << ans << '\n';
	for (int i = 1; i <= n; i++) if (c[i]) cout << i << ' ';
	return 0;
}


Comments

Submit
0 Comments
More Questions

520A - Pangram
124A - The number of positions
1041A - Heist
901A - Hashing Trees
1283A - Minutes Before the New Year
1654D - Potion Brewing Class
1107B - Digital root
25A - IQ test
785A - Anton and Polyhedrons
1542B - Plus and Multiply
306A - Candies
1651C - Fault-tolerant Network
870A - Search for Pretty Integers
1174A - Ehab Fails to Be Thanos
1169A - Circle Metro
780C - Andryusha and Colored Balloons
1153A - Serval and Bus
1487C - Minimum Ties
1136A - Nastya Is Reading a Book
1353B - Two Arrays And Swaps
1490E - Accidental Victory
1335A - Candies and Two Sisters
96B - Lucky Numbers (easy)
1151B - Dima and a Bad XOR
1435B - A New Technique
1633A - Div 7
268A - Games
1062B - Math
1294C - Product of Three Numbers
749A - Bachgold Problem